const KoaRouter = require('koa-router');
const { postData } = require('../../libs/body');
const fs = require('fs');
const pathLib = require('path');

let tasks = JSON.parse(fs.readFileSync(pathLib.resolve(__dirname, '../../data/task.json')));

const router = new KoaRouter({
    prefix: '/task'
});

router.get('/', async (ctx, next) => {
    ctx.body = '您访问的是首页';
});

router.get('/query', async ctx => {
    if (!tasks) {
        ctx.body = {
            code: 1,
            msg: '任务查询失败',
            data: {}
        };
    } else {
        ctx.body = {
            code: 0,
            msg: '任务查询成功',
            data: tasks.datas
        };
    }
});

router.post('/add', postData(), async (ctx, next) => {
    let { title } = ctx.request.fields;
    
    if (!title) {
        ctx.body = {
            code: 2,
            msg: '任务标题不能为空',
            data: {}
        };
    } else {
        let newTask = {
            ID: ++tasks._id,
            title,
            done: false
        };

        tasks.datas.unshift(newTask);

        ctx.body = {
            code: 0,
            msg: '任务添加成功',
            data: newTask
        };

        fs.writeFileSync(pathLib.resolve(__dirname, '../../data/task.json'), JSON.stringify(tasks));
    }
});

router.post('/update', postData(), async ctx => {
    let { id } = ctx.request.fields;

    if (!id) {
        ctx.body = {
            code: 3,
            msg: '任务ID不能为空',
            data: {}
        };
    } else {
        let todo = tasks.datas.find(item => item.ID == id);
        todo.done = !todo.done;

        ctx.body = {
            code: 0,
            msg: '任务修改成功',
            data: todo
        };

        fs.writeFileSync(pathLib.resolve(__dirname, '../../data/task.json'), JSON.stringify(tasks));
    }
});

router.post('/delete', postData(), async (ctx, next) => {
    let { id } = ctx.request.fields;

    if (!id) {
        ctx.body = {
            code: 3,
            msg: '任务ID不能为空',
            data: {}
        };
    } else {
        // tasks.datas = tasks.datas.filter(item => item.ID != id);
        tasks.datas.splice(tasks.datas.findIndex(item => item.ID == id), 1);

        ctx.body = {
            code: 0,
            msg: '任务删除成功',
            data: tasks.datas
        };

        fs.writeFileSync(pathLib.resolve(__dirname, '../../data/task.json'), JSON.stringify(tasks));
    }
});

module.exports = router.routes();